<template>
  <view class="container">

    <view class="search-box">
      <u-search
        placeholder="搜索供应商名称"
        v-model="searchKey"
        @search="handleSearch"
        @clear="handleSearch"
      ></u-search>
    </view>

    <view class="list">
      <u-cell-group>
        <u-cell
          v-for="item in supplierList"
          :key="item.id"
          :title="item.name"
          :value="`佣金: ${(item.agent_commission * 100).toFixed(2)}%`"
          isLink
          @click="handleSupplierDetail(item.id)"
        >
          <template #icon>
            <u-icon name="account" size="20"></u-icon>
          </template>
        </u-cell>
      </u-cell-group>

      <u-loadmore
        :status="loadStatus"
        :icon-type="iconType"
        :load-text="loadText"
      />
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { agentSupplier } from "@/common/apis/agent.js";
import { useStore } from "vuex";

const store = useStore();
const supplierList = ref([]);
const searchKey = ref("");
const currentPage = ref(1);
const totalPage = ref(1);
const loadStatus = ref("loadmore");
const iconType = ref("circle");
const loadText = ref({
  loadmore: "上拉加载更多",
  loading: "正在加载...",
  nomore: "没有更多了",
});

async function fetchSupplierList() {
  loadStatus.value = "loading";
  try {
    const response = await agentSupplier({
      page: currentPage.value,
      search: searchKey.value,
    });

    if (currentPage.value === 1) {
      supplierList.value = response.data.records;
    } else {
      supplierList.value.push(...response.data.records);
    }

    totalPage.value = response.data.total_page;
    loadStatus.value =
      response.data.total_page > currentPage.value ? "loadmore" : "nomore";
  } catch (error) {
    console.error(error);
    loadStatus.value = "loadmore";
  }
}

function handleSearch() {
  currentPage.value = 1;
  fetchSupplierList();
}

function handleSupplierDetail(id) {
  uni.navigateTo({
    url: `/pages/agenter/supplier-detail?id=${id}`,
  });
}

onMounted(() => {
  fetchSupplierList();
});
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;

  .search-box {
    margin-bottom: 20rpx;
  }

  .list {
    background: #fff;
    border-radius: 16rpx;
    padding: 20rpx;
  }
}
</style>
